package com.shxc.smarttrade.old.foreignfragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.adapternew.AlphaHistoryAdapter;
import com.shxc.smarttrade.old.bean.AlphaHistoryBean;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.myview.MyFootView;
import com.shxc.smarttrade.old.myview.MyRefreshHeadView;
import com.shxc.smarttrade.old.myview.RecycleViewDivider;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.Logger;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.zhy.autolayout.AutoLinearLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/11/9.
 */

public class AlphaHistoryFragment extends Fragment {

    @BindView(R.id.tv_explain_text)
    TextView tvExplainText;
    @BindView(R.id.ll_nodata_bg)
    AutoLinearLayout llNodataBg;
    @BindView(R.id.x_recycler_view)
    XRecyclerView xRecyclerView;
    private View rootView;
    private LinearLayoutManager manager;
    private boolean isRefresh = false;//xRecycleView是否在刷新中
    private int page = 1;
    private List<AlphaHistoryBean.DataBean.HistoryOrderBean> allList = new ArrayList<>();
    private AlphaHistoryAdapter adapter;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (xRecyclerView != null)
                        xRecyclerView.refreshComplete();
                    if (isRefresh) {
                        allList.clear();
                        adapter.notifyDataSetChanged();
                    }
                    List<AlphaHistoryBean.DataBean.HistoryOrderBean> mbList = (List<AlphaHistoryBean.DataBean.HistoryOrderBean>) msg.obj;
                    if (mbList != null && mbList.size() != 0) {
                        allList.addAll(mbList);
                        adapter.setDatas(allList);

                    } else {
                        if (xRecyclerView != null)
                            xRecyclerView.setNoMore(true);
                        if (allList.size() != 0)
                            BaseUtils.showToast("已加载全部!", getActivity());
                    }
                    isRefresh = false;
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_super_man, null);
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        ButterKnife.bind(this, rootView);
        initView();
        initListener();
        initData();
        return rootView;
    }

    private void initView() {
        manager = new LinearLayoutManager(getContext());
        xRecyclerView.setLayoutManager(manager);
        xRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayout.VERTICAL, 20, getResources().getColor(R.color.all_background)));
        xRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
        MyRefreshHeadView myRefreshHeadView = new MyRefreshHeadView(getContext());
        myRefreshHeadView.setArrowImageView(R.mipmap.indicator_arrow);
        xRecyclerView.setRefreshHeader(myRefreshHeadView);
        xRecyclerView.setFootView(new MyFootView(getContext()));
        xRecyclerView.setAdapter(adapter = new AlphaHistoryAdapter(getContext()));

    }

    private void initListener() {
        xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isRefresh = true;
                        page = 1;
                        initData();
                    }
                }, 1000);

            }

            @Override
            public void onLoadMore() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page++;
                        initData();
                    }
                }, 1000);

            }
        });
    }

    private void initData() {
        String accessToken = SpUtils.getString(getActivity(), "accessToken", "");
        int eaId = getActivity().getIntent().getIntExtra("eaId", -1);
        Map<String, Object> map = new HashMap<>();
        map.put("eaId", String.valueOf(eaId));
        map.put("accessToken", accessToken);
        map.put("page", String.valueOf(page));
        map.put("pageSize", "10");
        MyOkHttpUtils.getServiceDatas(getActivity(),map, URLContents.ALPHA_DATA_FRAGMENT_EAHISTORY, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                Logger.e("exception", e.getMessage());

                BaseUtils.showToast("网络异常", getActivity());
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    Gson gson = new Gson();
                    AlphaHistoryBean abi = gson.fromJson(response, AlphaHistoryBean.class);
                    if (abi.getErr_code().equals("0")) {
                        Message msg = Message.obtain();
                        msg.what = 0;
                        msg.obj = abi.getData().getHistoryOrder();
                        handler.sendMessage(msg);

                    } else
                        BaseUtils.showToast(abi.getErr_msg(), getActivity());
                }

            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
